package main

import (
	"context"
	"flag"
	libLog "log"
	"os"
	"time"

	"github.com/libp2p/go-libp2p"
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/multiformats/go-multiaddr"
)

var (
	serverAddr string
	log        = libLog.New(os.Stderr, "", libLog.Llongfile)
)

func init() {
	flag.StringVar(&serverAddr, "s", "", "-s <server addr>")
	flag.Parse()
}

func main() {
	h, err := libp2p.New(context.Background())
	if err != nil {
		log.Panic(err)
	}

	addr := h.Addrs()[0].String()
	addr += "/p2p/"
	addr += h.ID().Pretty()
	log.Println(addr)

	buffer := make([]byte, 1<<20)
	if serverAddr == "" {
		log.Println("here")
		h.SetStreamHandler("test", func(s network.Stream) {
			log.Println("here")
			defer s.Reset()
			for {
				log.Println("here")
				n, err := s.Read(buffer)
				if err != nil {
					log.Println(err)
					break
				}
				log.Println(string(buffer[:n]))
			}
		})
		log.Println("here")
	} else {
		log.Println("here")
		ma, err := multiaddr.NewMultiaddr(serverAddr)
		if err != nil {
			log.Panic(err)
		}
		pi, err := peer.AddrInfoFromP2pAddr(ma)
		if err != nil {
			log.Panic(err)
		}
		err = h.Connect(context.Background(), *pi)
		if err != nil {
			log.Panic(err)
		}

		s, err := h.NewStream(context.Background(), pi.ID, "test")
		if err != nil {
			log.Panic(err)
		}

		log.Printf("var: %#+v\n", s)

		s.Write([]byte("Hello"))
		time.Sleep(time.Second)
		s.Reset()
		log.Println("here")
	}

	select {}
}
